/*jQuery(function ($) {
        $(".login-social").tooltip()
});*/

var userApp = angular.module('userApp', ['ajoslin.promise-tracker' , 'ui.bootstrap']);

userApp.directive('match',['$parse', function ($parse) {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, elem, attrs, ctrl) {
//This part does the matching
            scope.$watch(function() {
                return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || $parse(attrs.match)(scope) === ctrl.$modelValue;
            }, function(currentValue) {
                ctrl.$setValidity('match', currentValue);
            });

//This part is supposed to check the strength
            /*
            ctrl.$parsers.unshift(function(viewValue) {
                var pwdValidLength, pwdHasLetter, pwdHasNumber;

                pwdValidLength = (viewValue && viewValue.length >= 6 ? true : false);
                pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? true : false;
                pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? true : false;

                if( pwdValidLength && pwdHasLetter && pwdHasNumber ) {
                    ctrl.$setValidity('pwd', true);
                } else {
                    ctrl.$setValidity('pwd', false);                    
                }
                return viewValue;
            });*/
        },
    };
}]);

userApp.directive('uniqueEmail', ['$http', function($http) {  
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      scope.busy = false;
      scope.$watch(attrs.ngModel, function(value) {
        
        // hide old error messages
        ctrl.$setValidity('isTaken', true);
        //ctrl.$setValidity('invalidChars', true);
        
        if (!value) {
          // don't send undefined to the server during dirty check
          // empty username is caught by required directive
          return;
        } 
        
        scope.busy = true;
        
        $http({
            method  : 'POST',
            url     : base_url + 'user/check_email' ,
            data    : $.param( { email: value } ) ,// { email: value } ,  // pass in data as strings
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' } ,  // set the headers so angular passing info as form data (not request payload)
           
            } )
            .success(function(data) {
                console.log('data = ' , data.isTaken);             
                // display new error message
                if (data.isTaken) {
                  ctrl.$setValidity('isTaken', false);
                } else if (data.invalidChars) {
                  //ctrl.$setValidity('invalidChars', false);
                }

                scope.busy = false;
            })
            .error(function(data) {
                 // display new error message
                if (data.isTaken) {
                  ctrl.$setValidity('isTaken', false);
                } else if (data.invalidChars) {
                  ctrl.$setValidity('invalidChars', false);
                }
                scope.busy = false;          
            });        
      })
    }
  }
}]);

userApp.controller('signupController' , function signupController($scope , $http , promiseTracker , $log , $timeout) {					
        // create a blank object to hold our form information
        // $scope will allow this to pass between controller and view

    $scope.signup = {};

    // process the form
    $scope.signupProcess = function( form ) {
        $scope.submitted = true;

        // If form is invalid, return and let AngularJS show validation errors.
        if ($scope.signupForm.$invalid) { 
            var field = null,
                firstError = null;
            for (field in $scope.signupForm) {
                if (field[0] != '$')
                {
                    if (firstError === null && !$scope.signupForm[field].$valid) {
                        firstError = $scope.signupForm[field].$name;
                    }

                    if ($scope.signupForm[field].$pristine) {
                        $scope.signupForm[field].$dirty = true;
                    }
                }
            }
            
            signupForm[firstError].focus();
            return;
        }


        if( $scope.signupForm.$valid) { 
            
            console.log('$scope.signup = ' , $scope.signup);
                //$scope.signupForm.email.$setValidity('havemail', false);
                //console.log('$scope.signupForm = ' , $scope.signupForm);
                //$scope.signupForm.name.$setValidity('invalid' , false);
                //$scope.signupForm.name.$invalid = data.errors.user.name;
                //$scope.errorSuperhero = data.errors.superheroAlias;
                //return false;

                //$scope.loading = true;
                //$scope.submit = false;
                $scope.loadingTracker = promiseTracker('loadingTracker');

          //use `addPromise` to add any old promise to our tracker
            $scope.delaySomething = function() {
                var promise = $timeout(function() {
                alert('Delayed something!');
                }, 1000);
                $scope.loadingTracker.addPromise(promise);
            };

            

            $http({
                method  : 'POST',
                url     : base_url + 'user/create' ,
                data    : $.param($scope.signup),  // pass in data as strings
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' } ,  // set the headers so angular passing info as form data (not request payload)
                tracker: $scope.loadingTracker 
                } )
                .success(function(data) {
                    console.log(data);

                    if (!data.success) {
                        // if not successful, bind errors to error variables
                        console.log('field = ' , data.name_error);
                        angular.forEach(data.name_error, function(value) {
                            field = value.field;
                            ngshow_error = value.ngshow;
                            
                            $scope.signupForm[field].$setValidity(ngshow_error , false);                            
                            if ($scope.signupForm[field].$pristine) {
                                $scope.signupForm[field].$dirty = true;
                            }                           
                        })
                        signupForm[data.name_error[0].field].focus();
                    } 
                    else {
                        $scope.submitted = false;
                        // if successful, bind success message to message
                        $scope.message = data.message;
                        $scope.signupForm.$setPristine();
                        $scope.signup = '';;
                        //$scope.signup = defaultForm;
                    }
            });

        }
        else{ 
            console.log('Errors in form data');
            ///$scope.signupForm.name.$setValidity('required', false);
        }
    };

});


userApp.controller('loginController' , function loginController($scope , $http , promiseTracker , $log , $timeout , $location) {					
    // create a blank object to hold our form information
    // $scope will allow this to pass between controller and view

    $scope.login = {};
    
    $scope.loginProcess = function( form ) {        
        $scope.submitted = true;
        console.log('$scope.loginForm = ' , $scope.loginForm);

        // If form is invalid, return and let AngularJS show validation errors.
        if ($scope.loginForm.$invalid) { 
            var field = null,
            firstError = null;
            for (field in $scope.loginForm) {
                if (field[0] != '$')
                {
                    if (firstError === null && !$scope.loginForm[field].$valid) {
                        firstError = $scope.loginForm[field].$name;
                    }

                    if ($scope.loginForm[field].$pristine) {
                        $scope.loginForm[field].$dirty = true;
                    }
                }
            }            
            loginForm[firstError].focus();
            return;
        }
        $scope.loadingTracker = promiseTracker('loadingTracker');
        $scope.delaySomething = function() {
            var promise = $timeout(function() {
            alert('Delayed something!');
            }, 1000);
            $scope.loadingTracker.addPromise(promise);
        };

            

        $http({
            method  : 'POST',
            url     : base_url + 'user/check_login' ,
            data    : $.param($scope.login),  // pass in data as strings
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' } ,  // set the headers so angular passing info as form data (not request payload)
            tracker: $scope.loadingTracker 
            } )
            .success(function(data) {
                console.log(data);

                if (!data.success) {
                    // if not successful, bind errors to error variables
                    console.log('field = ' , data.name_error);
                    if(data.name_error){
                        angular.forEach(data.name_error, function(value) {
                            field = value.field;
                            ngshow_error = value.ngshow;

                            //$scope.loginForm[field].$setValidity(ngshow_error , false);                            
                            if ($scope.loginForm[field].$pristine) {
                                //$scope.loginForm[field].$dirty = true;
                            }                           
                        })
                        //loginForm[data.name_error[0].field].focus();
                    }
                    $scope.message = data.message;
                } 
                else {
                    $scope.submitted = false;
                    // if successful, bind success message to message
                    $scope.message = data.message;
                    $scope.loginForm.$setPristine();
                    $scope.login = '';                     
                    window.location.reload();          
                    //$scope.signup = defaultForm;
                }
        });
    };    
    
    $scope.forgotPasswordProcess = function forgotPasswordProcess( form ){
        $scope.submitted = true;
        // If form is invalid, return and let AngularJS show validation errors.       
        if ($scope.forgotPasswordForm.$invalid) { 
            var field = null,
            firstError = null;
            for (field in $scope.forgotPasswordForm) {
                if (field[0] != '$')
                {
                    if (firstError === null && !$scope.forgotPasswordForm[field].$valid) {
                        firstError = $scope.forgotPasswordForm[field].$name;
                    }

                    if ($scope.forgotPasswordForm[field].$pristine) {
                        $scope.forgotPasswordForm[field].$dirty = true;
                    }
                }
            }            
            forgotPasswordForm[firstError].focus();
            event.preventDefault();
            return;
        }
    }
    
    $scope.restorePasswordProcess = function restorePasswordProcess( form ){
        $scope.submitted = true;
        // If form is invalid, return and let AngularJS show validation errors.       
        if ($scope.restorePasswordForm.$invalid) { 
            var field = null,
            firstError = null;
            for (field in $scope.restorePasswordForm) {
                if (field[0] != '$')
                {
                    if (firstError === null && !$scope.restorePasswordForm[field].$valid) {
                        firstError = $scope.restorePasswordForm[field].$name;
                    }

                    if ($scope.restorePasswordForm[field].$pristine) {
                        $scope.restorePasswordForm[field].$dirty = true;
                    }
                }
            }            
            restorePasswordForm[firstError].focus();
            event.preventDefault();
            return;
        }
    }
    
    
    $scope.loginSocial = function loginSocial( url ){
        screenY    = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
        outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth,
        outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22),
        width    = 500,
        height   = 300,
        left     = (window.screen.width / 2) - ((width / 2) + 10),
        top      = (window.screen.height / 2) - ((height / 2) + 50) , 
        features = (
           'width=' + width +
           ',height=' + height +
           ',left=' + left +
           ',top=' + top
         );
        var popupWidth=500;
        var popupHeight=300;
        var xPosition=(jQuery(window).width()-popupWidth)/2;
        var yPosition=(jQuery(window).height()-popupHeight)/2;
        var loginUrl = base_url + url;

        googleLoginWindow=window.open(loginUrl , "LoginWindow", 
            "location=1,scrollbars=1,"+
            "width="+popupWidth+",height="+popupHeight+","+
            "left="+xPosition+",top="+yPosition + ",screenX=" + left + ",screenY="
            + screenY + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
        return false;
    }
});
    